import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/adminlogin',
    name: 'AdminLogin',
    component: () => import('../views/AdminLogin.vue'),
    meta: { admin: true, title: '后台管理系统' }
  },
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('../views/Admin.vue'),
    meta: { admin: true, title: '后台管理系统' }
  },
  {
    path: '/',
    name: 'Home',
    component: HomeView
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue'),
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// beforeEach:路由前置守卫,路由发生变化前触发
router.beforeEach((to, from, next) => {
  document.title = to.meta.title
  if (to.path === '/admin') {
    let adminname = sessionStorage.getItem('adminname')
    if (adminname !== 'admin') return next('/adminlogin')
  }
  next(); //放行:允许路由跳转,类似express的拦截器中间件
})
export default router
